package com.qyhl.module_home.home.search;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.mobstat.StatService;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.module_home.utils.aboutrecyclerview.HistortyAdapter;
import com.qyhl.module_home.utils.aboutrecyclerview.HistoryItemTouchHelper;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.home.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * 搜索
 */
@Route(path = ARouterPathConstant.SEARCH)
public class SearchActivity extends BaseActivity implements SearchContract.SearchView {
    @BindView(R2.id.history_recyclerView)
    RecyclerView history_recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.listview)
    RecyclerView listview;
    @BindView(R2.id.loading_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.search_edit)
    EditText search_edit;
    @BindView(R2.id.gosearch)
    TextView gosearch;
    @BindView(R2.id.cleartext)
    ImageView cleartext;
    @BindView(R2.id.clear_history)
    ImageView clear_history;
    @BindView(R2.id.history_layout)
    RelativeLayout history_layout;

    @Autowired(name = "catalogId")
    String catalogId;

    @Autowired(name = "subCatalog")
    int subCatalog;

    private SearchPresenter mPresenter;
    private String mKeyWord;//关键字
    private String newsId = "0";//分页用的id
    private List<GlobalNewsBean> mDataList;
    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;
    private List<String> lastSearches = new ArrayList<>();//历史记录
    private HistortyAdapter histortyAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.WHITE);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

    }


    @Override
    protected int getContentView() {
        return R.layout.home_activity_search2;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SearchPresenter(this);
        initView();
        setHistory();
        setListeners();
    }

    @Override
    protected void setListener() {

    }

    private void setHistory() {
        //初始化搜索框
        if (Hawk.contains("history")) { //设置历史内容
            lastSearches = Hawk.get("history");
        }
        histortyAdapter = new HistortyAdapter(lastSearches);
        history_recyclerView.setLayoutManager(new LinearLayoutManager(this));
        history_recyclerView.setItemAnimator(new DefaultItemAnimator());
        HistoryItemTouchHelper historyItemTouchHelper = new HistoryItemTouchHelper(histortyAdapter);
        historyItemTouchHelper.attachToRecyclerView(history_recyclerView);
        history_recyclerView.setAdapter(histortyAdapter);
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            gosearch.setBackground(ContextCompat.getDrawable(this, R.drawable.home_ripple_click));
        }
        mDataList = new ArrayList<>();
        refresh.setEnableLoadMore(true);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setDisableContentWhenRefresh(true);

        mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listview.setLayoutManager(linearLayoutManager);
        listview.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                history_layout.setVisibility(View.GONE);
                history_recyclerView.setVisibility(View.GONE);
                GlobalNewsBean bean = mDataList.get(position);
                ItemSkipUtils.getInstance().itemSkip(bean, SearchActivity.this);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void setListeners() {
        search_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                history_layout.setVisibility(View.VISIBLE);
                history_recyclerView.setVisibility(View.VISIBLE);
            }
        });
        //重新获取
        loadingMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingMask.setReloadButtonText("加载中...");
                if (StringUtils.isEmpty(catalogId)) {
                    mPresenter.getData(mKeyWord, "0");
                } else {
                    mPresenter.getList(mKeyWord, "0", catalogId, subCatalog);
                }

            }
        });

        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (StringUtils.isEmpty(catalogId)) {
                    mPresenter.getData(mKeyWord, "0");
                } else {
                    mPresenter.getList(mKeyWord, "0", catalogId, subCatalog);
                }
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (StringUtils.isEmpty(catalogId)) {
                    mPresenter.getData(mKeyWord, newsId);
                } else {
                    mPresenter.getList(mKeyWord, newsId, catalogId, subCatalog);
                }
            }
        });

        //搜索
        gosearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                history_layout.setVisibility(View.GONE);
                history_recyclerView.setVisibility(View.GONE);
                if (StringUtils.isEmpty(mKeyWord)) {
                    Toasty.normal(SearchActivity.this, "关键字不能为空！", Toast.LENGTH_SHORT).show();
                } else {
                    if (StringUtils.isEmpty(catalogId)) {
                        mPresenter.getData(mKeyWord, "0");
                    } else {
                        mPresenter.getList(mKeyWord, "0", catalogId, subCatalog);
                    }
                    //四川融媒统计
                    if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145)) {
                        StatisticsMainInit.searchLog(CommonUtils.getInstance().getUserName(), mKeyWord);
                    }
                }
            }
        });

        //历史监听
        histortyAdapter.setOnItemClickListener(new HistortyAdapter.OnItemViewClickListener() {
            @Override
            public void ClickListener(int position) {
                search_edit.setText(lastSearches.get(position));
                //将光标移至文字末尾
                search_edit.setSelection(lastSearches.get(position).length());

                if (StringUtils.isEmpty(catalogId)) {
                    mPresenter.getData(lastSearches.get(position).toString(), "0");
                } else {
                    mPresenter.getList(lastSearches.get(position).toString(), "0", catalogId, subCatalog);
                }

                history_layout.setVisibility(View.GONE);
                history_recyclerView.setVisibility(View.GONE);
            }
        });

        cleartext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search_edit.setText("");
            }
        });

        clear_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lastSearches.clear();
                histortyAdapter.notifyDataSetChanged();
            }
        });

        search_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mKeyWord = editable.toString();
            }
        });


        listview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                history_layout.setVisibility(View.GONE);
                history_recyclerView.setVisibility(View.GONE);
            }
        });

        search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    history_layout.setVisibility(View.GONE);
                    history_recyclerView.setVisibility(View.GONE);
                    if (StringUtils.isEmpty(mKeyWord)) {
                        Toasty.normal(SearchActivity.this, "关键字不能为空！", Toast.LENGTH_SHORT).show();
                    } else {
                        if (StringUtils.isEmpty(catalogId)) {
                            mPresenter.getData(mKeyWord, "0");
                        } else {
                            mPresenter.getList(mKeyWord, "0", catalogId, subCatalog);
                        }
                        hideInput();
                        //四川融媒统计
                        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145)) {
                            StatisticsMainInit.searchLog(CommonUtils.getInstance().getUserName(), mKeyWord);
                        }
                    }
                }
                return false;
            }
        });


    }

    @Override
    public void setData(List<NewsBean> beanList, boolean isMore) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadingMask.setStatus(LoadingLayout.Success);
        loadingMask.setReloadButtonText("点击重试~~");
        List<GlobalNewsBean> indexList = new ArrayList<>();
        if (!lastSearches.contains(mKeyWord) && !TextUtils.isEmpty(mKeyWord)) {
            if (lastSearches.size() >= 8) {
                lastSearches.remove(0);
            }
            lastSearches.add(mKeyWord);
        }
        histortyAdapter.notifyDataSetChanged();
        int globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
        int globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
        //全局新闻样式配置
        for (int i = 0; i < beanList.size(); i++) {
            if ("2".equalsIgnoreCase(beanList.get(i).getType())) {
                beanList.get(i).setCommonStyle(globalCommon);
                beanList.get(i).setVideoStyle(globalVideo);
            }
        }
        if (beanList.size() > 0) {
            newsId = beanList.get(beanList.size() - 1).getID();
        } else {
            return;
        }
        //数据模型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            //是否是无图
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    style = bean.getCommonStyle();
                    break;
                case "2"://图片新闻
                    type = "2";
                    if (bean.getImagess().size() == 1) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() == 2) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() >= 3) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        pThree = bean.getImagess().get(2).getImageUrlString();
                        hasPicture = true;
                    } else {
                        hasPicture = false;
                    }
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }

        //更新数据源
        if (isMore) {
            mDataList.addAll(indexList);
        } else {
            mDataList.clear();
            mDataList.addAll(indexList);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadingMask.setEmptyText(msg);
        loadingMask.setStatus(LoadingLayout.Empty);
        loadingMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadingMask.setNoNetworkText(msg);
        loadingMask.setStatus(LoadingLayout.No_Network);
        loadingMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadingMask.setStatus(LoadingLayout.Success);
        loadingMask.setReloadButtonText("点击重试~~");
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadingMask.setStatus(LoadingLayout.Error);
        loadingMask.setReloadButtonText("点击重试~~");
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(this);
        StatService.onPageStart(this, "搜索页");
        //umeng
        MobclickAgent.onPageStart("搜索页");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.SEARCH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(this);
        StatService.onPageEnd(this, "搜索页");
        //umeng
        MobclickAgent.onPageEnd("搜索页");
        MobclickAgent.onPause(this);
        ActionLogUtils.getInstance().onPause(this, ActionConstant.SEARCH);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Hawk.put("history", lastSearches);//存储历史记录
    }


}